﻿#include "bookmarkmanager.h"
#include<QtDebug>
#include<QDir>
#include<QJsonDocument>
#include<QJsonArray>
#include<QUrl>

BookmarkManager::BookmarkManager()
{
    qDebug()<<"c++ test defaultname";
}

BookmarkManager::BookmarkManager(QString name)
{
    qDebug()<<"c++ test name";
   qDebug()<<"bookmark manager ctor:"<<QDir::currentPath();
   file.setFileName(QDir::currentPath()+"/userfolder/"+name+"/bookmark.json");
   if(!file.open(QIODevice::ReadWrite))
       qDebug()<<"open file failed";
   QJsonDocument jsonDoc=QJsonDocument::fromJson(file.read(file.size()));
   QJsonObject jsonObject=jsonDoc.object();
   QJsonArray items=jsonObject.value("bookmark").toArray();
   for(auto item : items)
   {
       QJsonObject dataObject=item.toObject();
       qDebug()<<dataObject.value("title").toString();
       BookmarkItem bookmarkItem(dataObject.value("url").toString(),dataObject.value("title").toString(),
                               dataObject.value("iconUrl").toString());
       list.append(QVariant::fromValue(bookmarkItem));
   }

}

BookmarkManager::~BookmarkManager()
{
    qDebug()<<"bookmark manager dtor";
    file.remove();
   QJsonObject jsonObject;
   QJsonArray arr;
   QJsonArray bookmarkArr;
   for(auto x :list)
   {
       QJsonObject dataObject;
       BookmarkItem item=x.value<BookmarkItem>();
       dataObject.insert("url", item.url());
       dataObject.insert("title",item.title());
       dataObject.insert("iconUrl",item.icon());
       bookmarkArr.push_back(dataObject);
   }
   jsonObject.insert("bookmark",bookmarkArr);
   QJsonDocument jsonDoc(jsonObject);

   if(!file.open(QIODevice::WriteOnly))
       qDebug()<<"open file failed";
   file.write(jsonDoc.toJson());
   file.close();

}

QVariantList BookmarkManager::getBookmarkItemList()
{
    return list;
}

void BookmarkManager::add(QString url, QString icon, QString title)
{
    if(isFavorited(url))
        return;
    BookmarkItem item(url,title,icon);
    list.append(QVariant::fromValue(item));
}

void BookmarkManager::remove(QString url)
{
    qDebug()<<"c++ test"<<url;
    for(auto &x : list)
    {
        BookmarkItem item=x.value<BookmarkItem>();
        qDebug()<<item.url();
        if(item.url()==url){
            list.removeOne(x);
            qDebug()<<"c++ test"<<url;
        }

    }
}

bool BookmarkManager::isFavorited(QString url)
{
    for(auto &x : list)
    {
        BookmarkItem item=x.value<BookmarkItem>();
        if(item.url()==url)
            return true;
    }
    return false;
}
